layui.config({
	base : "js/"
}).use(['form','layer','jquery','laypage'],function(){
	var form = layui.form(),
		layer = parent.layer === undefined ? layui.layer : parent.layer,
		laypage = layui.laypage,
		$ = layui.jquery;

	//加载页面数据
	var usersData = '';
	
	var orgId = window.sessionStorage.getItem("organizeId");
	console.log("manager/list.js");
	
	$.get($.httpRootPath()+"/api/web/manager/i/"+orgId+"/org", function(data){
	})
	.success(function(data) {
		usersData = JSON.parse(data).data;
		//执行加载数据的方法
		usersList();
	})
  	.error(function(e) {
  		if(e.status == "401"){
  			layer.alert('你不是该团队的创始人，不能查看该模块',{icon:2, title:'友情提示'});
  		}
  	})
  	.complete(function() { });

	//添加会员
	$(".infoAdd_btn").click(function(){
		var s = getRelation(orgId);
		if(s != 1){
			layer.msg("您没有权限");
			return;
		}
		var index = layui.layer.open({
			title : "添加组织",
			type : 2,
			area: ['450px', '200px'],
			content : "add.html",
			success : function(layero, index){
				setTimeout(function(){
					layui.layer.tips('点击此处返回会员列表', '.layui-layer-setwin .layui-layer-close', {
						tips: 3
					});
				},500)
			}
		})
		//改变窗口大小时，重置弹窗的高度，防止超出可视区域（如F12调出debug的操作）
		$(window).resize(function(){
			layui.layer.full(index);
		})
	})

	//批量删除
	$(".batchDel").click(function(){
		var $checkbox = $('.users_list tbody input[type="checkbox"][name="checked"]');
		var $checked = $('.users_list tbody input[type="checkbox"][name="checked"]:checked');
		if($checkbox.is(":checked")){
			layer.confirm('确定删除选中的信息？',{icon:3, title:'提示信息'},function(index){
				var index = layer.msg('选择中，请稍候',{icon: 16,time:false,shade:0.8});
	            setTimeout(function(){
	            	//删除数据
	            	for(var j=0;j<$checked.length;j++){
	            		for(var i=0;i<usersData.length;i++){
							if(usersData[i].newsId == $checked.eq(j).parents("tr").find(".news_del").attr("data-id")){
								usersData.splice(i,1);
								usersList(usersData);
							}
						}
	            	}
	            	$('.users_list thead input[type="checkbox"]').prop("checked",false);
	            	form.render();
	                layer.close(index);
					layer.msg("删除成功");
	            },2000);
	        })
		}else{
			layer.msg("请选择需要删除的管理员");
		}
	})

    //全选
	form.on('checkbox(allChoose)', function(data){
		var child = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="show"])');
		child.each(function(index, item){
			item.checked = data.elem.checked;
		});
		form.render('checkbox');
	});

	//通过判断文章是否全部选中来确定全选按钮是否选中
	form.on("checkbox(choose)",function(data){
		var child = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="show"])');
		var childChecked = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="show"]):checked')
		if(childChecked.length == child.length){
			$(data.elem).parents('table').find('thead input#allChoose').get(0).checked = true;
		}else{
			$(data.elem).parents('table').find('thead input#allChoose').get(0).checked = false;
		}
		form.render('checkbox');
	})

	//操作
	$("body").on("click",".info_edit",function(){  //编辑
		layer.alert('该信息由成员自己维护',{icon:6, title:'友情提示'});
	})

	$("body").on("click",".info_del",function(){  //删除
		var _this = $(this);
		layer.confirm('确定删除此用户？',{icon:3, title:'提示信息'},function(index){
			var manId =_this.attr("data-id");
			var data = {
				mid:manId,
				orgId:orgId
			}
			var del = deleteInfo(data,function(){
				layer.close(index);
			})
			if(del){
				_this.parents("tr").remove();
			}
		});
	})
	

	function usersList(){
		//渲染数据
		function renderDate(data,curr){
			var dataHtml = '';
			currData = usersData.concat().splice(curr*nums-nums, nums);
//			currData = usersData;
			if(currData.length != 0){
				for(var i=0;i<currData.length;i++){
					var dataHt = "";
					if(currData[i].relation == 1){
			    		dataHt += '<td style="color:#f00">'+'FOUNDER'+'</td>';
			    	}else if(currData[i].relation == 0){
			    		dataHt += '<td style="color:#44BB74">'+'MANAGER'+'</td>';
			    	}else{
			    		dataHt += '<td>'+'NO_RELATION'+'</td>';
			    	}
					dataHtml += '<tr>'
			    	+  '<td><input type="checkbox" name="checked" lay-skin="primary" lay-filter="choose"></td>'
			    	+  '<td>'+currData[i].account+'</td>'
			    	+  '<td>'+currData[i].name+'</td>'
					+  '<td>'+currData[i].email+'</td>'
			    	+  '<td>'+currData[i].mobile+'</td>'
			    	+  dataHt
			    	+  '<td>'+currData[i].loginTime+'</td>'
			    	+  '<td>'
					+    '<a class="layui-btn layui-btn-mini info_edit" data-id="'+currData[i].id+'"><i class="iconfont icon-edit"></i> 编辑</a>'
					+    '<a class="layui-btn layui-btn-danger layui-btn-mini info_del" data-id="'+currData[i].id+'"><i class="layui-icon">&#xe640;</i> 删除</a>'
				
			        +  '</td>'
			    	+'</tr>';
				}
			}else{
				dataHtml = '<tr><td colspan="8">暂无数据</td></tr>';
			}
		    return dataHtml;
		}

		//分页
		var nums = 10; //每页出现的数据量
		laypage({
			cont : "page",
			pages : Math.ceil(usersData.length/nums),
			jump : function(obj){
				$(".users_content").html(renderDate(usersData,obj.curr));
				$('.users_list thead input[type="checkbox"]').prop("checked",false);
		    	form.render();
			}
		})
	}
        
})

function deleteInfo(data,callback) {
	var del = false;
	data._method= 'DELETE'
    $.ajax({
        url: $.httpRootPath()+"/api/web/manager/i/"+data.orgId+"/org",
        type: 'POST',
        dataType: 'json',
        data: data,
        timeout: 15000,
        cache: false,
        async:false,
        success: function (r) {
            if (r.code == "00") {
            	del = true;
              	layer.msg("删除成功！");
            } else {
               layer.msg(r.msg);
            }
        },
        error: function (e) {
          layer.msg("系统错误！");
        },
        complete:function(){
        	callback();
        }
    });
    return del;
   }

function getRelation(oid){
	var real = "-1"
	$.ajax({
		url: $.httpRootPath() + '/api/web/manager/getRelation',
		type: 'GET',
		dataType: 'json',
		data: {"oid": oid},
		timeout: 15000,
		async: false,
		success: function(reply) {
			if(reply.code == "00") {
				console.log(reply.msg+" "+ reply.data);
				real = reply.data;
			}
		},
		error: function(e) {
			layer.msg("未知错误", {icon: 0});
		}
	});
	return real;
};